<template>
  <div class="register">
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field 
          v-model="username" 
          name="uname" 
          label="用户名" 
          placeholder="请输入" />

      <van-field 
          v-model="password" 
          type="password" 
          name="upass" 
          label="密码" 
          placeholder="请输入" />

      <van-field 
          v-model="password2" 
          type="password" 
          name="upass2" 
          label="确认密码" 
          placeholder="请输入" />

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">立即注册</van-button>
      </div>

      <div>
        <router-link class="link" to="/login">已账号，马上登录?</router-link>
      </div>
    </van-form>
    <!--使用组件 跳转首页 -->
    <back-to></back-to>
  </div>
</template>

<script>
import BackTo from '@/components/BackTo.vue';
import { Toast, Dialog } from 'vant';

export default {
  components: {
    BackTo
  },
  data() {
    return {
      username: '',
      password: '',
      password2: '',
      sky_users: []
    };
  },
  created() {
    const sky_users_str = localStorage.getItem("SKY_USERS");
    this.sky_users = sky_users_str ? JSON.parse(sky_users_str) : [];
  },
  methods: {
    onSubmit() {
      const { username: uname, password: upass, password2: upass2 } = this;

      // 验证输入
      const validationMessage = this.validateInput(uname, upass, upass2);
      if (validationMessage) {
        Toast(validationMessage);
        return false;
      }

      // 检查用户是否已经存在
      if (this.sky_users.some(user => user.username === uname)) {
        Toast(`"${uname}"已存在，不需要重新注册`);
        return false;
      }

      // 注册用户
      this.registerUser(uname, upass);
    },
    validateInput(uname, upass, upass2) {
      if (!uname || !upass || !upass2) return '输入框不能为空~';
      if (!/^[0-9a-zA-Z_]{4,8}@qq.com$/.test(uname)) return '请输入邮箱格式文本';
      if (upass.length < 6) return '密码需要6位字符以上';
      if (upass !== upass2) return '两次输入的密码不一致';
      return '';
    },
    registerUser(uname, upass) {
      const obj = {
        id: `${Math.random().toString().slice(2)}_${Date.now()}`,
        username: uname,
        password: upass
      };

      // 存储新用户
      this.sky_users.push(obj);
      localStorage.setItem('SKY_USERS', JSON.stringify(this.sky_users));

      // 提示并跳转
      Dialog.alert({
        confirmButtonColor: "#0c8bf3",
        message: '注册成功，跳转登录。',
      }).then(() => {
        this.$router.push({ path: '/login' });
      });
    }
  }
};
</script>

<style lang="less">
.register {
  padding-top: 150px;
  .van-button--normal {
    background-color: #1EC28A;
    border: 0;
  }
  .link {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 16px;
  }
}
</style>
